package com.cnct.generic.dubbo.holder;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ReferenceConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import com.cnct.generic.dubbo.strategy.RequireReferenceStrategy;
import com.cnct.generic.dubbo.utils.KeyGenerateUtil;
import org.springframework.stereotype.Component;

/**
 * 直连方式
 * @author wangzhen
 */
@Component("directRequireReferenceStrategy")
public class DirectReferenConfig implements RequireReferenceStrategy {


    private ReferenceHolder referenceHolder;

    public DirectReferenConfig(ReferenceHolder referenceHolder){
        this.referenceHolder = referenceHolder;
    }

    @Override
    public ReferenceConfig requireReferenceConfig(ApplicationConfig application, RegistryConfig registry, String group, String url, String interfaceName, String version) {


        String key = KeyGenerateUtil.referenceKey(interfaceName, group, version);

        //从缓存中获取服务提供者的配置
        ReferenceConfig referenceConfig = referenceHolder.cache().getIfPresent(key);

        if (null == referenceConfig) {

            referenceConfig = referenceHolder.buildReferenceConfig(application, registry, group, version, interfaceName);

            //版本信息
            if (StringUtils.isNotEmpty(version)) {
                referenceConfig.setVersion(version);
            }

            //直连信息
            if (StringUtils.isNotEmpty(url)) {
                referenceConfig.setUrl(url + "/" + interfaceName);
            }

            referenceHolder.cache().put(key, referenceConfig);
        }

        return referenceConfig;
    }
}
